var timer = null;
$(document).ready(function() {
	//获取kettle信息
	$.ajax({
		url:BASE_URL_KETTLE_SLAVE_SERVER_CRUD,
		type:'get',
		async: false,
		dataType:'json',
		contentType:"application/json",
		success:function(data){
			$.each(data._embedded.kettleSlaveServers, function(i, item){
				var url = BASE_URL_KETTLE_SLAVE_SERVER_CRUD +'/'+item.id;
				if( i == "0")
				{
					getServiceInfo(BASE_URL_KETTLE_SLAVE_SERVER_CRUD +'/'+item.id);
					html = '<li><a href="javascript:void(0)" data-url="' + url + '" class="getServiceInfo active"><img id='+item.id+' src="../../../../images/icons/connectIcon.png" class="fl">'+item.name+'</a>'+'</li>';
				}else
				{
					html = '<li><a href="javascript:void(0)" data-url="' + url + '" class="getServiceInfo"><img id='+item.id+' src="../../../../images/icons/connectIcon.png" class="fl">'+item.name+'</a>'+'</li>';
				}
				$(".kettle_tree").append(html);

			});		
		}
	});
	
	//获取节点信息
	$.ajax({
		url:BASE_URL_NODE_CLUSTER_CRUD,
		type:"get",
		async: false,
		dataType:"json",
		contentType:"application/json",
		success:function(data){
			$.each(data._embedded.clusterNodes, function(i, item){
				var url = BASE_URL_NODE_CLUSTER_CRUD +'/'+item.id;
				html = '<li><a href="javascript:void(0)" data-url="' + url + '" class="getServiceInfo"><img id='+item.id+' src="../../../../images/icons/connectIcon.png" class="fl">'+item.name+'</a>'+'</li>';
				$(".kettle_tree").append(html);
			});	
		}
	});

	//定时检查服务器是否在线
	setInterval(checkNodeIsRunning,1000);	
});

function checkNodeIsRunning(){
	//检查kettle
	$.ajax({
		url:BASE_URL_KETTLE_SLAVE_SERVER +'/runningStatus',
		type:'get',
		async: false,
		dataType:'json',
		contentType:"application/json",
		success:function(data){
			var UnRunning = data.isNotRuning;
			for(var i = 0;i < UnRunning.length;i++){
				$('#'+UnRunning[i]).attr('src','../../../../images/icons/CrashIcon.png');
			}			
			var Running = data.isRuning;
			for(var i = 0;i < Running.length;i++){
				$('#'+Running[i]).attr('src','../../../../images/icons/connectIcon.png');
			}
		}
	});
	//检查节点
	$.ajax({
		url:BASE_URL_NODE_CLUSTER +'/runningStatus',
		type:"get",
		async: false,
		dataType:"json",
		contentType:"application/json",
		success:function(data){
			var UnRunning = data.isNotRuning;
			for(var i = 0;i < UnRunning.length;i++){
				$('#'+UnRunning[i]).attr('src','../../../../images/icons/CrashIcon.png');
			}		
			var Running = data.isRuning;
			for(var i = 0;i < Running.length;i++){
				$('#'+Running[i]).attr('src','../../../../images/icons/connectIcon.png');
			}
		}
	});
}

$("body").delegate(".getServiceInfo","click",function(e){
	var url = $(this).data("url");
	$(".getServiceInfo").removeClass("active");
	$(this).addClass("active");
	//清除之前的定时任务，节省开销
	if(timer!=null){
		clearInterval(timer);
	}
	getServiceInfo(url);
});

function getServiceInfo(url){
	if(url.indexOf('clusterNodes')!=-1){
		$.ajax({
			url:url,
			type:"get",
			dataType:"json",
			contentType:"application/json",
			success:function(data){	
				$("#name").html(data.name);
				$("#ipaddr").html(data.ipaddr);
				$("#port").html(data.port);
				//获取CPU和内存信息
				var dataParam = {
						ipaddr : data.ipaddr,
						port : data.port
				};
				NodeServiceInformationDisplay(dataParam);
			}
		});		
	}else{
		$.ajax({
			url:url,
			type:'get',
			dataType:'json',
			contentType:"application/json",
			success:function(data){	
				$("#name").html(data.name);
				$("#ipaddr").html(data.hostName);
				$("#port").html(data.port);
				var dataParam = {
						ipaddr : data.hostName,
						port : data.port
				};
				NodeServiceInformationDisplay(dataParam);
			}
		});
	}
}

function NodeServiceInformationDisplay(dataParam){
	//清除之前的定时任务，节省开销
	if(timer!=null){
		clearInterval(timer);
	}
	timer = setInterval(function(){ServiceInformationDisplay(dataParam);},1000);
	function ServiceInformationDisplay(dataParam){
		$.ajax({
			url:BASE_URL_NODE_CLUSTER +'/runningInformations',
			type:"get",
			data:dataParam,
			dataType:"json",
			contentType:"application/json",
			success:function(result){
				if(!chart || !chart.series){
					 return;
				 }
				 var series = chart.series[0];//cpu使用率曲线图
				 if(!chart1 || !chart1.series){
					 return;
				 }	
				var series1 = chart1.series[0];	//内存使用率曲线图
				var x = (new Date()).getTime(),   //时间轴    
				y = Math.random();			
				
				if(result.node){
					//将数据显示出来		
					series.addPoint([x, result.cpu], true, true);
					series1.addPoint([x,result.memory],true,true);
				}else{
					series.addPoint([x, 0], true, true);
					series1.addPoint([x,0],true,true);
				}
			}
		});		
	}
	
	//报表echart
	Highcharts.setOptions({
		global: {
			useUTC: false
		}
	});
	    
	//cpu使用率曲线图
	var chart;
	chart = new Highcharts.Chart({
		chart: {
			renderTo: 'container',
			type: 'spline',
			animation: Highcharts.svg,
			// don't animate in old IE               
			marginRight: 10,
			events: {
				load: function() {}
			}
		},
		title: {
			text: 'CPU',
			x: 0 //center
		},
		subtitle: {
			/* text: '平均值：5.6%',
	            x: 0*/
		},
		credits: {
			enabled: false
		},
		xAxis: {
			type: 'datetime',
			tickPixelInterval: 150
		},
		yAxis: [{
			min : 0,
			max : 100,
			title: {
				text: '使用率 (%)'
			},
			plotLines: [{
				value: 0,
				width: 1,
				color: '#808080'
			}]
		}],
		tooltip: {
			formatter: function() {
				return '<b>' + this.series.name + '</b><br/>' + Highcharts.dateFormat('%Y-%m-%d %H:%M:%S', this.x) + '<br/>' + Highcharts.numberFormat(this.y, 2) + '%';
			}
		},
		legend: {
			enabled: false
		},
		exporting: {
			enabled: false
		},
		series: [{
			name: 'CPU使用率',
			data: (function() { // generate an array of random data                             
				var data = [],
				time = (new Date()).getTime(),
				i;
				for (i = -19; i <= 0; i++) {
					data.push({
						x: time + i * 1000,
						y: 0
					});
				}
				return data;
			})()
		}]
	}); 

	//内存使用曲线图
	var chart1;
	chart1 = new Highcharts.Chart({
		chart: {
			renderTo: 'chart2',
			type: 'spline',
			animation: Highcharts.svg,
			// don't animate in old IE               
			marginRight: 10,
			events: {
				load: function() {}
			}
		},
		title: {
			text: '物理内存',
			x: 0 //center
		},
		subtitle: {
			/*text: '平均值：2201.11(MB)',
		        x: 0*/
		},
		credits: {
			enabled: false
		},
		xAxis: {
			type: 'datetime',
			tickPixelInterval: 150
		},
		yAxis: [{
			min : 0,
			title: {
				text: '使用内存 (MB)'
			},
			plotLines: [{
				value: 0,
				width: 1,
				color: '#808080'
			}]
		}],
		tooltip: {
			formatter: function() {
				return '<b>使用内存：</b>'+
				this.y + 'MB';	        	
			}
		},
		legend: {
			enabled: false
		},
		exporting: {
			enabled: false
		},
		series: [{
			name: 'Random data',
			data: (function() { // generate an array of random data                             
				var data = [],
				time = (new Date()).getTime(),
				i;
				for (i = -19; i <= 0; i++) {
					data.push({
						x: time + i * 1000,
						y: 0
					});
				}
				return data;
			})()
		}]
	});
	
}

function KettleServiceInformationDisplay(connectUrl){
	//清除之前的定时任务，节省开销
	if(timer!=null){
		clearInterval(timer);
	}
	var sock = SockJsCreator(connectUrl)
	sock.onopen = function() {
	     sock.send('test');
	 };
	 sock.onmessage = function(e) {
		 var Data = JSON.parse(e.data); 
		 //alert("json:"+Data.cpu.totalPerc);
		 if(!chart || !chart.series){
			 return;
		 }
		 var series = chart.series[0];
		 if(!chart1 || !chart1.series){
			 return;
		 }
		 var series1 = chart1.series[0];
		 var x = (new Date()).getTime(),
         // current time         
         y = Math.random();
         series.addPoint([x, Data.cpu.totalPerc], true, true);
         series1.addPoint([x,Data.memory.used],true,true);
	     //console.log('message', e.data);
	 };
	 sock.onclose = function() {
	     //console.log('close');
	 };
	 
	//报表echart
	 Highcharts.setOptions({
	 	global: {
	 		useUTC: false
	 	}
	 });
	     
	 //cpu使用率曲线图
	 var chart;
	 chart = new Highcharts.Chart({
	 	chart: {
	 		renderTo: 'container',
	 		type: 'spline',
	 		animation: Highcharts.svg,
	 		// don't animate in old IE               
	 		marginRight: 10,
	 		events: {
	 			load: function() {}
	 		}
	 	},
	 	title: {
	 		text: 'CPU',
	 		x: 0 //center
	 	},
	 	subtitle: {
	 		/* text: '平均值：5.6%',
	             x: 0*/
	 	},
	 	credits: {
	 		enabled: false
	 	},
	 	xAxis: {
	 		type: 'datetime',
	 		tickPixelInterval: 150
	 	},
	 	yAxis: [{
	 		min : 0,
			max : 100,
	 		title: {
	 			text: '使用率 (%)'
	 		},
	 		plotLines: [{
	 			value: 0,
	 			width: 1,
	 			color: '#808080'
	 		}]
	 	}],
	 	tooltip: {
	 		formatter: function() {
	 			return '<b>' + this.series.name + '</b><br/>' + Highcharts.dateFormat('%Y-%m-%d %H:%M:%S', this.x) + '<br/>' + Highcharts.numberFormat(this.y, 2) + '%';
	 		}
	 	},
	 	legend: {
	 		enabled: false
	 	},
	 	exporting: {
	 		enabled: false
	 	},
	 	series: [{
	 		name: 'CPU使用率',
	 		data: (function() { // generate an array of random data                             
	 			var data = [],
	 			time = (new Date()).getTime(),
	 			i;
	 			for (i = -19; i <= 0; i++) {
	 				data.push({
	 					x: time + i * 1000,
	 					y: 0
	 				});
	 			}
	 			return data;
	 		})()
	 	}]
	 }); 

	 //内存使用率曲线图
	 var chart1;
	 chart1 = new Highcharts.Chart({
	 	chart: {
	 		renderTo: 'chart2',
	 		type: 'spline',
	 		animation: Highcharts.svg,
	 		// don't animate in old IE               
	 		marginRight: 10,
	 		events: {
	 			load: function() {}
	 		}
	 	},
	 	title: {
	 		text: '物理内存',
	 		x: 0 //center
	 	},
	 	subtitle: {
	 		/*text: '平均值：2201.11(MB)',
	 	        x: 0*/
	 	},
	 	credits: {
	 		enabled: false
	 	},
	 	xAxis: {
	 		type: 'datetime',
	 		tickPixelInterval: 150
	 	},
	 	yAxis: [{
	 		min: 0,
	 		title: {
	 			text: '使用内存 (MB)'
	 		},
	 		plotLines: [{
	 			value: 0,
	 			width: 1,
	 			color: '#808080'
	 		}]
	 	}],
	 	tooltip: {
	 		formatter: function() {
	 			return '<b>使用内存：</b>'+
	 			this.y + 'MB';	        	
	 		}
	 	},
	 	legend: {
	 		enabled: false
	 	},
	 	exporting: {
	 		enabled: false
	 	},
	 	series: [{
	 		name: 'Random data',
	 		data: (function() { // generate an array of random data                             
	 			var data = [],
	 			time = (new Date()).getTime(),
	 			i;
	 			for (i = -19; i <= 0; i++) {
	 				data.push({
	 					x: time + i * 1000,
	 					y: 0
	 				});
	 			}
	 			return data;
	 		})()
	 	}]
	 });
}


